package org.openea.eap.module.obpm.controller.form;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.api.query.QueryFilter;
import org.openbpm.base.api.query.QueryOP;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.PropertyUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.db.model.page.PageResult;
import org.openbpm.base.rest.BaseController;
import org.openbpm.base.rest.util.RequestUtil;
import org.openbpm.bus.api.service.IBusinessObjectService;
import org.openbpm.form.api.model.FormType;
import org.openea.eap.module.obpm.service.form.FormDefManager;
import org.openea.eap.module.obpm.service.form.FormTemplateManager;
import org.openea.eap.module.obpm.model.form.FormDef;
import org.openbpm.sys.api.service.SysConnectRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping({"/form/formDef/"})
public class FormDefController
        extends BaseController<FormDef> {
    @Autowired
    FormDefManager formDefManager;
    @Autowired
    IBusinessObjectService businessObjectService;
    @Autowired
    FormTemplateManager formTemplateManager;
    @Autowired
    SysConnectRecordService sysConnectRecordService;

    @RequestMapping({"listJson"})
    public PageResult listJson(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String formType = RequestUtil.getString(request, "formType", FormType.PC.value());
        QueryFilter queryFilter = getQueryFilter(request);
        queryFilter.addFilter("type_", formType, QueryOP.EQUAL);
        Page<Map> pageList = (Page<Map>) this.formDefManager.queryWithBo(queryFilter);

        return new PageResult((List) pageList);
    }


    @RequestMapping({"save"})
    @CatchErr(write2response = true, value = "保存表单失败")
    public ResultMsg<String> save(@RequestBody FormDef formDef) throws Exception {
        if (StringUtil.isEmpty(formDef.getKey()) && this.formDefManager.getByKey(formDef.getKey()) != null) {
            throw new BusinessMessage("表单 KEY 已经存在，请修改 表单 KEY 的 值");
        }

        ResultMsg<String> msg = super.save(formDef);
        this.formDefManager.saveBackupHtml(formDef);
        return msg;
    }


    @RequestMapping({"getObject"})
    @CatchErr(write2response = true, value = "获取formDef异常")
    public ResultMsg<JSONObject> getObject(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = RequestUtil.getString(request, "id");
        String key = RequestUtil.getString(request, "key");
        FormDef formDef = null;
        if (StringUtil.isNotEmpty(id)) {
            formDef = (FormDef) this.formDefManager.get(id);
        } else if (StringUtil.isNotEmpty(key)) {
            formDef = this.formDefManager.getByKey(key);
        }

        boolean isCopy = "copy".equalsIgnoreCase(RequestUtil.getString(request, "openType"));
        if(isCopy){
            formDef.setId(null);
            key = formDef.getKey();
            int n = key.lastIndexOf("_v");
            String strV = "";
            if(n>0){
                // v+1
                String oldV = key.substring(n);
                strV = "_v" + (1+Integer.parseInt("0"+ key.substring(n+2)));
                formDef.setKey(key.replace(oldV, strV));
                formDef.setName(formDef.getName().replace(oldV, strV));
            }else{
                strV = "_v1";
                formDef.setKey(key+strV);
                formDef.setName(formDef.getName()+strV);
            }
        }

        JSONObject json = (formDef == null) ? new JSONObject() : (JSONObject) JSON.toJSON(formDef);

        json.put("isDeveloper", Boolean.valueOf(StringUtil.isNotEmpty(PropertyUtil.getFormDefBackupPath())));

        return getSuccessResult(json);
    }


    @RequestMapping({"getBackupHtml"})
    @CatchErr(write2response = true, value = "获取开发者备份html异常")
    public ResultMsg<String> getBackupHtml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = RequestUtil.getString(request, "id");
        String key = RequestUtil.getString(request, "key");
        FormDef formDef = null;
        if (StringUtil.isNotEmpty(id)) {
            formDef = (FormDef) this.formDefManager.get(id);
        } else if (StringUtil.isNotEmpty(key)) {
            formDef = this.formDefManager.getByKey(key);
        }
        return getSuccessResult(this.formDefManager.getBackupHtml(formDef));
    }


    @RequestMapping({"boTreeData"})
    @ResponseBody
    public Object boTreeData(@RequestParam String boKey) throws Exception {
        return this.businessObjectService.boTreeData(boKey);
    }


    @RequestMapping({"templateData"})
    @CatchErr(write2response = true, value = "根据bo获取表单模板信息异常")
    public ResultMsg<JSONArray> templateData(@RequestParam String boKey, @RequestParam String type) throws Exception {
        JSONArray array = this.formTemplateManager.templateData(boKey, type);

        return new ResultMsg(array);
    }


    @RequestMapping({"createHtml"})
    @CatchErr(write2response = true, value = "生成html异常")
    public ResultMsg<String> createHtml(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONArray jsonArray) throws Exception {
        String boKey = RequestUtil.getString(request, "boKey");
        String formType = RequestUtil.getString(request, "formType");
        String isSubTable = RequestUtil.getString(request, "isSubTable");

        String html = this.formDefManager.generateFormHtml(boKey, jsonArray, formType, StringUtil.isNotEmpty(isSubTable));
        return getSuccessResult(html, "生成成功");
    }

    @RequestMapping({"genColumnHtml"})
    @CatchErr(write2response = true, value = "生成Column的HTML")
    public ResultMsg<String> genColumnHtml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String boKey = RequestUtil.getString(request, "boCode");
        String formType = RequestUtil.getString(request, "formType");
        String columnKey = RequestUtil.getString(request, "columnKey");
        String tableKey = RequestUtil.getString(request, "tableKey");
        String html = this.formDefManager.genColumnHtml(boKey, formType, tableKey, columnKey);
        return getSuccessResult(html, "生成成功");
    }

    @RequestMapping({"remove"})
    @CatchErr
    public ResultMsg<String> remove(@RequestParam String id) throws Exception {
        String[] aryIds = StringUtil.getStringAryByStr(id);

        for (String formId : aryIds) {
            FormDef form = (FormDef) this.formDefManager.get(formId);
            if (form != null) {
                this.sysConnectRecordService.checkIsRelatedWithBusinessMessage(form.getKey(), "BPM-DEF-FORM");
            }
        }

        this.formDefManager.removeByIds(aryIds);
        return getSuccessResult(String.format("删除%s成功", new Object[]{getModelDesc()}));
    }


    protected String getModelDesc() {
        return "自定义表单";
    }
}
